package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.dto.InterfaceExtParamDto;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysInterfaceDict;
import com.ysd.lis.entity.SysInterfaceMethExtParam;
import com.ysd.lis.entity.SysInterfaceMethod;
import com.ysd.lis.mapper.SysInterfaceDictMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMethExtParamMapper;
import com.ysd.lis.service.SysInterfaceMethExtParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * <p>
 * 接口场景外源语句参数对照 服务实现类
 * </p>
 *
 * @author cfz
 * @since 2024-04-26
 */
@Service
public class SysInterfaceMethExtParamServiceImpl extends ServiceImpl<SysInterfaceMethExtParamMapper, SysInterfaceMethExtParam> implements SysInterfaceMethExtParamService {
    @Autowired
    SysInterfaceMethExtParamMapper sysInterfaceMethExtParamMapper;
    @Autowired
    SysInterfaceDictMapper sysInterfaceDictMapper;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Override
    public Result findSysInterfaceMethExtParamList(SysInterfaceMethExtParam sysInterfaceMethExtParam) {
        List<SysInterfaceMethExtParam> list = findSysInterfaceMethExtParamArray(sysInterfaceMethExtParam);
        return Result.succ(1, "请求成功", list);
    }

    @Override
    public List<SysInterfaceMethExtParam> findSysInterfaceMethExtParamArray(SysInterfaceMethExtParam sysInterfaceMethExtParam) {
        MPJLambdaWrapper<SysInterfaceMethExtParam> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(SysInterfaceMethExtParam::getDelFlag, 0);


//        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getExtCode()), SysInterfaceMethExtParam::getExtCode, sysInterfaceMethExtParam.getExtCode());
//        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getExtCodeDtype()), SysInterfaceMethExtParam::getExtCodeDtype, sysInterfaceMethExtParam.getExtCodeDtype());
//        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getExtCodeNa()), SysInterfaceMethExtParam::getExtCodeNa, sysInterfaceMethExtParam.getExtCodeNa());
//        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getExtCodeDes()), SysInterfaceMethExtParam::getExtCodeDes, sysInterfaceMethExtParam.getExtCodeDes());
//        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getInCodeNo()), SysInterfaceMethExtParam::getInCodeNo, sysInterfaceMethExtParam.getInCodeNo());
//        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getInCodeNa()), SysInterfaceMethExtParam::getInCodeNa, sysInterfaceMethExtParam.getInCodeNa());
//        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getInCodeId()), SysInterfaceMethExtParam::getInCodeId, sysInterfaceMethExtParam.getInCodeId());
//        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getInCodeDtype()), SysInterfaceMethExtParam::getInCodeDtype, sysInterfaceMethExtParam.getInCodeDtype());
//        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getInCodeDes()), SysInterfaceMethExtParam::getInCodeDes, sysInterfaceMethExtParam.getInCodeDes());
        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getInterfaceId()), SysInterfaceMethExtParam::getInterfaceId, sysInterfaceMethExtParam.getInterfaceId());
        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getInterfaceMethodId()), SysInterfaceMethExtParam::getInterfaceMethodId, sysInterfaceMethExtParam.getInterfaceMethodId());
        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getInterfaceMethodDictId()), SysInterfaceMethExtParam::getInterfaceMethodDictId, sysInterfaceMethExtParam.getInterfaceMethodDictId());
        queryWrapper.eq(StringUtils.isNotBlank(sysInterfaceMethExtParam.getOrgId()), SysInterfaceMethExtParam::getOrgId, sysInterfaceMethExtParam.getOrgId());
        queryWrapper.eq(!BeanUtil.isEmpty(sysInterfaceMethExtParam.getIsEnable()), SysInterfaceMethExtParam::getIsEnable, sysInterfaceMethExtParam.getIsEnable());
        queryWrapper.eq(!BeanUtil.isEmpty(sysInterfaceMethExtParam.getSeq()), SysInterfaceMethExtParam::getSeq, sysInterfaceMethExtParam.getSeq());
        queryWrapper.like(StringUtils.isNotBlank(sysInterfaceMethExtParam.getKeyValue()), SysInterfaceMethExtParam::getExtCode, sysInterfaceMethExtParam.getKeyValue());

        queryWrapper.orderByAsc(SysInterfaceMethExtParam::getSeq);

        return sysInterfaceMethExtParamMapper.selectList(queryWrapper);
    }

    @Override
    public Result addSysInterfaceMethExtParam(SysInterfaceMethExtParam sysInterfaceMethExtParam) {
        int i = sysInterfaceMethExtParamMapper.insert(sysInterfaceMethExtParam);
        if (i > 0) {
            return Result.succ(1, "新增成功", sysInterfaceMethExtParam);
        }
        return Result.fail("新增失败");
    }

    /*批量操作，更新、新增*/
    @Override
    public Result batchSaveSysInterfaceMethExtParam(List<SysInterfaceMethExtParam> sysInterfaceMethExtParams) {
        List<SysInterfaceMethExtParam> listAdd = new ArrayList<>();
        List<SysInterfaceMethExtParam> listEdt = new ArrayList<>();
        for (SysInterfaceMethExtParam m : sysInterfaceMethExtParams) {
            try {
                if (m.getExtCode().indexOf("-") > -1) {
                    String s = m.getExtCode().split("-")[1];
                    String code = m.getExtCode().split("-")[0];
                    byte[] bytes = code.getBytes();
                    int asciiSum = 0;
                    for (byte b : bytes) {
                        asciiSum += b;
                    }
                    if (s.indexOf("(") > -1) {
                        String ss = s.split("\\(")[0];
                        m.setSeq(asciiSum * 100 + Integer.parseInt(ss));
                    } else {
                        m.setSeq(asciiSum * 100 + Integer.parseInt(s));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (BeanUtil.isEmpty(m.getId())) {
                listAdd.add(m);
            } else {
                listEdt.add(m);
            }

        }
        boolean r = true;

        if (!listAdd.isEmpty()) {
            r = this.saveBatch(listAdd);
        }
        if (!listEdt.isEmpty()) {
            r = this.updateBatchById(listEdt);
        }
        return !r ? Result.fail("更新失败") : Result.succ(1, "操作成功", sysInterfaceMethExtParams);
    }

    /*批量删除*/
    @Override
    public Result batchDeleteSysInterfaceMethExtParam(List<SysInterfaceMethExtParam> sysInterfaceMethExtParams) {
        boolean r = true;
        for (SysInterfaceMethExtParam m : sysInterfaceMethExtParams) {
            m.setDelFlag(1);
        }

        r = this.updateBatchById(sysInterfaceMethExtParams);

        return !r ? Result.fail("更新失败") : Result.succ(1, "删除成功", sysInterfaceMethExtParams);
    }

    @Override
    public Result deleteSysInterfaceMethExtParam(SysInterfaceMethExtParam sysInterfaceMethExtParam) {
        sysInterfaceMethExtParam.setDelFlag(1);
        int i = sysInterfaceMethExtParamMapper.updateById(sysInterfaceMethExtParam);
        if (i > 0) {
            return Result.succ(1, "删除成功", sysInterfaceMethExtParam);
        }
        return Result.fail("删除失败");
    }

    @Override
    public Result updateSysInterfaceMethExtParam(SysInterfaceMethExtParam sysInterfaceMethExtParam) {
        int i = sysInterfaceMethExtParamMapper.updateById(sysInterfaceMethExtParam);
        if (i > 0) {
            return Result.succ(1, "更新成功", sysInterfaceMethExtParam);
        }
        return Result.fail("更新失败");
    }

    @Override
    public JSONObject execExtParam(InterfaceExtParamDto dto) {
        List<SysInterfaceMethExtParam> extParamList = dto.getExtParamList();
        String methodId = dto.getMethodId();

        MPJLambdaWrapper<SysInterfaceDict> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(SysInterfaceDict.class)
                .leftJoin(SysInterfaceMethod.class, "sm", SysInterfaceMethod::getInterfaceDictId, SysInterfaceDict::getId)
                .eq(SysInterfaceDict::getDelFlag, 0)
                .eq(SysInterfaceMethod::getId, methodId);
        SysInterfaceDict dict = sysInterfaceDictMapper.selectOne(queryWrapper);
        String url = dict.getUrl();
        Map map = new HashMap();
        for (SysInterfaceMethExtParam param : extParamList) {
            String inCodeNo = param.getInCodeNo();
            String inValue = param.getInValue();
            map.put(inCodeNo, inValue);
        }
        String s = JSONObject.toJSONString(map);

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        String returnMsg = "";
        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {
                    returnMsg = HttpUtil.createPost(webUrl + url + "Test").body(s).contentType("application/json").execute().body();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("接口管理平台异常,请检查");
        }
        JSONObject jsonObject = JSON.parseObject(returnMsg);
        return jsonObject;
    }
}
